package common

import (
	"crypto/md5"
	"encoding/hex"
	"math/rand"
	"strings"
	"time"

	uuid "github.com/satori/go.uuid"
)

// UUID 生成UUID
func UUID() string {
	id := uuid.Must(uuid.NewV4())
	return id.String()
}

// GenPass 生成密码MD5
func GenPass(pwd string, salt string) string {
	pass := MD5(pwd + salt)
	return MD5(salt + pass)
}

// MD5 生成32位MD5
func MD5(text string) string {
	ctx := md5.New()
	ctx.Write([]byte(text))
	return hex.EncodeToString(ctx.Sum(nil))
}

// Salt return len=8 random string
func Salt() string {
	return Random(8)
}

// Random 生成不重复随机字符串
func Random(len int) string {
	source := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	slen := strings.Count(source, "") - 1
	bytes := []byte(source)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))

	for i := 0; i < len; i++ {
		rint := r.Intn(slen)
		exist := false
		for j := range result {
			if result[j] == bytes[rint] {
				exist = true
				break
			}
		}
		if !exist {
			result = append(result, bytes[rint])
		} else {
			i--
		}
	}
	return string(result)
}
